
import { useUpdateEffect } from '@umijs/hooks';
import { Button, Drawer } from 'antd';
import { Spin, List, Row, Col } from 'antd';
import { getAgentRootPath, getDirectory, getFileText, agentSaveFileText } from '../service';
import { useRequestHandle } from '@/utils/utils';
import { CloudServerOutlined, FolderFilled, FileFilled, RollbackOutlined } from '@ant-design/icons';
import { useState } from 'react';
import styles from './index.less';
import { Input } from 'antd';
import { message } from 'antd';
import ScriptEdit from "@/components/ScriptEdit";



const EditFile = (props) => {
    const { modalVisible, onCancel, loading, record, id } = props;


    const [directoryList, setDirectoryList] = useState([]);
    const [lastDirectory, setLastDirectory] = useState([]);
    const [hoverDirectory, setHoverDirectory] = useState("");
    const [searchValue, setSearchValue] = useState("");
    const [filePath, setFilePath] = useState("");
    const [innerRecord, setInnerRecord] = useState({ code: "" });
    const getAgentRootPathRequest = useRequestHandle(getAgentRootPath, (data) => {

        const tmp = data.map(item => {
            return {
                label: item,
                value: item,
                icon: <CloudServerOutlined />,
            }
        });
        if (!record.id) {
            setHoverDirectory(tmp[0].value);
        }
    });
    const getDirectoryRequest = useRequestHandle(getDirectory, (data) => {
        setDirectoryList(data);
    });
    const getFileTextRequest = useRequestHandle(getFileText, (data) => {

        setInnerRecord({ code: data });
    });
    const agentSaveFileTextRequest = useRequestHandle(agentSaveFileText, () => {
        message.success("保存成功");
    });
    useUpdateEffect(() => {
        if (modalVisible) {
            getAgentRootPathRequest.run({ id })
        }
    }, [modalVisible])
    useUpdateEffect(() => {
        if (record.id) {
            const pathArray = record.rootPath.split("\\");
            
            let hoverDir = "";
             for (let i = 0; i < pathArray.length; i++) {
                 hoverDir += `${pathArray[i]}\\`;
             }
            setHoverDirectory(hoverDir);
        }
    }, [record])
    useUpdateEffect(() => {
        if (hoverDirectory) {
            getDirectoryRequest.run({ id, path: hoverDirectory })
        }
    }, [hoverDirectory]);
    useUpdateEffect(() => {
        if (filePath) {
            getFileTextRequest.run({ id, path: filePath })
        }
    }, [filePath])
    let tmpDirectoryList = directoryList;
    if (searchValue) {
        tmpDirectoryList = tmpDirectoryList.filter(item => item.path.indexOf(searchValue) !== -1)
    }
    return (
        <Drawer
            destroyOnClose
            title={'修改文件'}
            open={modalVisible}
            // onCancel={() => onCancel()}
            onClose={() => onCancel()}
            width={"80%"}
            footer={null}
        >
            <Spin tip="正在处理..." spinning={loading || getDirectoryRequest.loading}>

                <div style={filePath ? { display: "none" } : {}}>
                    <div style={{ marginBottom: "12px" }}>
                        选择文件 (大于<span style={{ color: "red" }}>50KB</span>不支持在线编辑)：</div>
                   
                    <Input value={searchValue} onChange={
                        (e) => {
                            setSearchValue(e.target.value)
                        }
                    } style={{ marginBottom: "12px" }} placeholder='请输入关键字' />
                    <List
                        style={{ marginBottom: "12px" }}
                        size="small"
                        bordered
                        dataSource={lastDirectory && lastDirectory.length >= 1 ? [{ path: "..", type: 2 }, ...tmpDirectoryList] : tmpDirectoryList}
                        renderItem={(item) => <List.Item>
                            <div className={styles.directory}>
                                <span onClick={() => {
                                    if (item.type === 1) {
                                        if (item.kbSize && item.kbSize > 30) {
                                            message.error("大于30KB的文件不支持在线编辑");
                                            return;
                                        }
                                        setFilePath(item.path);
                                    }
                                    else {
                                        if (item.path === "..") {
                                            const lastPath = lastDirectory[lastDirectory.length - 1];
                                            const newLastDirectory = lastDirectory.slice(0, lastDirectory.length - 1);
                                            setLastDirectory(newLastDirectory);
                                            setHoverDirectory(lastPath);
                                        }
                                        else {
                                            if (item.canRead && item.canWrite) {
                                                const newLastDirectory = lastDirectory;
                                                newLastDirectory.push(hoverDirectory);
                                                setLastDirectory(newLastDirectory);
                                                setHoverDirectory(item.path);
                                            }
                                            else {
                                                message.error("无读取或者写入权限")
                                            }

                                        }
                                    }


                                }}>
                                    {item.type === 1
                                        ? <FileFilled style={{ color: "#ff21b9", marginRight: "4px", fontSize: "11px" }} />
                                        : <FolderFilled style={{ color: "#54aeff", marginRight: "4px" }} />}
                                    {item.path === ".." ? "" : <span>{item.path}
                                        <span style={item.canRead ? { color: "green", marginLeft: "10px", fontSize: "12px" } : { color: "red", marginLeft: "10px", fontSize: "12px" }}>读</span>
                                        <span style={item.canWrite ? { color: "green", marginLeft: "10px", fontSize: "12px" } : { color: "red", marginLeft: "10px", fontSize: "12px" }}>写</span>
                                    </span>}

                                    {item.type === 1
                                        ?
                                        <span style={item.kbSize < 50 ? { color: "green", marginLeft: "10px", fontSize: "12px" } : { color: "red", marginLeft: "10px", fontSize: "12px" }}>{item.size}</span>
                                        : null}
                                    <span style={{ fontSize: "12px", color: "#0083e3" }}>
                                        {item.path === ".." ? <>返回上一级<span style={{ marginLeft: "10px" }}>{lastDirectory[lastDirectory.length - 1]}</span></> : ""}</span>
                                </span>

                                {item.path !== ".." && item.canRead && item.canWrite && item.type === 1 ? <Button
                                    onClick={() => {
                                        if (item.kbSize && item.kbSize > 50) {
                                            message.error("大于50KB的文件不支持在线编辑");
                                            return;
                                        }
                                        setFilePath(item.path);
                                    }}
                                    size='small' style={{ float: "right" }}>修改</Button> : null}
                            </div></List.Item>}
                    />
                </div>
                <div style={!filePath ? { display: "none" } : {}}>
                    <p style={{ margin: "0 8 8px" }}>当前选中：{filePath}</p>
                    <Row>
                        <Col>  <Button size='small'
                            onClick={() => {
                                setFilePath("");
                                setInnerRecord({ code: "" });
                            }}
                            ghost type="link" icon={<RollbackOutlined />}>重新选择</Button> </Col>
                        <Col>    <Button size='small'
                            loading={agentSaveFileTextRequest.loading}
                            onClick={() => {
                                if (innerRecord.code) {
                                    agentSaveFileTextRequest.run({
                                        id,
                                        path: filePath,
                                        content: innerRecord.code
                                    });
                                }
                            }}
                            style={{ margin: "0 12px" }} type="primary">保存修改</Button></Col>
                    </Row>

                    <ScriptEdit
                        onValueChange={async (value) => {
                            setInnerRecord({ ...value });
                        }}
                        loading={false}
                        record={{ ...innerRecord }}
                    /></div>
            </Spin>
        </Drawer>
    );
};

export default EditFile;
